package bintree.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 二叉树的完全性检验
 * @author yuisama
 * @date 2022/02/21 17:35
 **/
public class Num958_IsCompleteTree {
    public boolean isCompleteTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean isSecondStep = false;
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (!isSecondStep) {
                if (cur.left != null && cur.right != null) {
                    queue.offer(cur.left);
                    queue.offer(cur.right);
                }else if (cur.left != null) {
                    queue.offer(cur.left);
                    isSecondStep = true;
                }else if (cur.right != null) {
                    return false;
                }else {
                    isSecondStep = true;
                }
            }else {
                // 第二阶段，所有节点都是叶子结点
                if (cur.left != null || cur.right != null) {
                    return false;
                }
            }
        }
        return true;
    }
}